const db = require('../config/database');

class Message {
  static async create({ senderId, receiverId, content }) {
    const [result] = await db.execute(
      'INSERT INTO messages (sender_id, receiver_id, content) VALUES (?, ?, ?)',
      [senderId, receiverId, content]
    );
    return result.insertId;
  }

  static async getConversation(userId1, userId2) {
    const [rows] = await db.execute(
      `SELECT m.*, 
        u1.username as sender_username,
        u2.username as receiver_username
       FROM messages m
       JOIN users u1 ON m.sender_id = u1.id
       JOIN users u2 ON m.receiver_id = u2.id
       WHERE (m.sender_id = ? AND m.receiver_id = ?)
       OR (m.sender_id = ? AND m.receiver_id = ?)
       ORDER BY m.created_at ASC`,
      [userId1, userId2, userId2, userId1]
    );
    return rows;
  }

  static async markAsRead(messageId, userId) {
    const [result] = await db.execute(
      'UPDATE messages SET status = "read" WHERE id = ? AND receiver_id = ?',
      [messageId, userId]
    );
    return result.affectedRows > 0;
  }

  static async getUnreadCount(userId) {
    const [rows] = await db.execute(
      'SELECT COUNT(*) as count FROM messages WHERE receiver_id = ? AND status = "unread"',
      [userId]
    );
    return rows[0].count;
  }
}

module.exports = Message; 